package com.xiran.srpingboottemplateself.service;

import com.xiran.srpingboottemplateself.pojo.dto.UserRegisterDTO;
import com.xiran.srpingboottemplateself.pojo.entity.User;
import com.xiran.srpingboottemplateself.pojo.vo.LoginRegisterVO;
import com.xiran.srpingboottemplateself.pojo.vo.LoginReqVO;
import com.xiran.srpingboottemplateself.pojo.vo.LoginRspVO;
import com.xiran.srpingboottemplateself.util.JwtTokenHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserService userService;
    private final PasswordEncoder passwordEncoder;
    private final JwtTokenHelper jwtTokenHelper;

    public LoginRspVO login(LoginReqVO loginReqVO) {
        // 查找用户
        User user = userService.findByUsername(loginReqVO.getUsername());
        log.info("username {} login", loginReqVO.getUsername());
        if (user == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginReqVO.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        }

        // 生成 Token
        String token = jwtTokenHelper.generateToken(user.getUsername());

        // 构建响应
        return LoginRspVO.builder()
                .token(token)
                .userId(user.getId())
                .username(user.getUsername())
                .role(user.getRole())
                .expiresIn(24 * 60 * 60L) // 24小时过期
                .build();
    }



}